import React, { useState, useEffect } from 'react';
import { ThinkingProcessProps } from '../types/thinking';
import { ThinkingProcessService } from '../services/thinkingProcessService';

interface EnhancedThinkingProcessProps extends ThinkingProcessProps {
  // Mock模式所需属性
  query?: string;
  customerInfo?: any;
  // Realtime模式所需属性 - 简化版本
  isThinking?: boolean;          // 外部传入：是否在思考状态
  thinkingContent?: string;      // 外部传入：思考内容
  isThinkingComplete?: boolean;  // 外部传入：思考是否完成
  isWaitingForThinking?: boolean; // 外部传入：是否等待第一个thinking chunk
}

export const ThinkingProcess: React.FC<EnhancedThinkingProcessProps> = ({ 
  type, 
  className = '', 
  mode = 'mock', 
  query = '', 
  customerInfo,
  // Realtime模式的外部状态
  isThinking = false,
  thinkingContent = '',
  isThinkingComplete = false,
  isWaitingForThinking = false
}) => {
  // Mock模式状态 - 简化，只使用字符串内容
  const [content, setContent] = useState<string>('');
  const [isLoading, setIsLoading] = useState(true);
  
  const isAuto = type === 'auto';

  // Mock模式的逻辑 - 简化为字符串内容
  useEffect(() => {
    if (mode === 'mock' && query) {
      console.log('[ThinkingProcess] 开始加载思考内容', { mode, query, type });
      
      const loadThinkingContent = async () => {
        setIsLoading(true);
        setContent('');
        
        try {          
          // 使用stream方法获取思考内容
          await ThinkingProcessService.getInstance().getThinkingStepsStream(
            query, 
            (newContent: string) => {
              setContent(newContent);
              // 一旦开始接收内容，就停止loading状态
              if (newContent && newContent.trim()) {
                setIsLoading(false);
              }
            }
          );
                    
        } catch (error) {
          console.error('❌ [ThinkingProcess] Failed to load thinking content:', error);
          setContent('思考过程生成失败，请重试...');
        } finally {
          console.log('🏁 [ThinkingProcess] 设置 isLoading = false');
          setIsLoading(false);
        }
      };

      loadThinkingContent();
    } else if (mode === 'realtime') {
      console.log('⚡ [ThinkingProcess] Realtime模式，跳过预加载');
      setIsLoading(false); // Realtime模式不需要预加载
    }
  }, [mode, query, type, customerInfo]);

  // 监听 content 变化
  useEffect(() => {
    console.log('🔍 [ThinkingProcess] content 变化:', content);
  }, [content]);

  // 监听 isLoading 变化
  useEffect(() => {
    console.log('⏳ [ThinkingProcess] isLoading 变化:', isLoading);
  }, [isLoading]);

  // Realtime模式渲染 - 简化版本，依赖外部状态
  if (mode === 'realtime') {
    // 不在思考状态且不在等待状态时不显示
    if (!isThinking && !isWaitingForThinking) {
      return null;
    }

    return (
      <div className={`max-w-xs px-3 py-2 rounded-lg ${
        isAuto ? 'bg-green-50 border-green-300' : 'bg-blue-50 border-blue-300'
      } text-gray-800 border ${className}`}>
        <div className="flex items-center gap-2 mb-2">
          <div className={`animate-spin w-3 h-3 border-2 ${
            isAuto ? 'border-green-500' : 'border-blue-500'
          } border-t-transparent rounded-full`} />
          <span className={`text-xs ${
            isAuto ? 'text-green-600' : 'text-blue-600'
          }`}>
            {isWaitingForThinking 
              ? 'AI正在深度思考...'
              : isThinkingComplete 
                ? '思考完成' 
                : 'AI正在深度思考...'
            }
          </span>
        </div>
        {thinkingContent && (
          <div className="text-sm">
            <div className={`text-sm text-gray-600`}>
              {thinkingContent.split('\n\n').map((paragraph, index) => (
                <div key={index} className={index > 0 ? 'mt-2' : ''}>
                  {paragraph}
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
    );
  }

  // 如果有内容，优先显示内容；否则显示loading或不显示
  if (!content) {
    // 没有内容时，如果在loading显示loading，否则不显示
    if (isLoading) {
      return (
        <div className={`max-w-xs px-3 py-2 rounded-lg ${
          isAuto ? 'bg-green-50 border-green-300' : 'bg-blue-50 border-blue-300'
        } text-gray-800 border ${className}`}>
          <div className="flex items-center gap-2">
            <div className={`animate-spin w-3 h-3 border-2 ${
              isAuto ? 'border-green-500' : 'border-blue-500'
            } border-t-transparent rounded-full`} />
            <span className={`text-xs ${
              isAuto ? 'text-green-600' : 'text-blue-600'
            }`}>
              思考中...
            </span>
          </div>
        </div>
      );
    }
    return null;
  }

  // 统一的渲染逻辑 - 直接显示字符串内容
  return (
    <div className={`max-w-xs px-3 py-2 rounded-lg ${
      isAuto ? 'bg-green-50 border-green-300' : 'bg-blue-50 border-blue-300'
    } text-gray-800 border ${className}`}>
      <div className="flex items-center gap-2 mb-2">
        <div className={`animate-spin w-3 h-3 border-2 ${
          isAuto ? 'border-green-500' : 'border-blue-500'
        } border-t-transparent rounded-full`} />
        <span className={`text-xs ${
          isAuto ? 'text-green-600' : 'text-blue-600'
        }`}>
          {isAuto ? 'AI正在自动分析客户问题...' : 'AI正在生成内容..'}
        </span>
      </div>
      <div className="text-xs">
        <div className={`text-xs text-gray-600`}>
          {content.split('\n').map((line, index) => (
            <div key={index} className={index > 0 ? 'mt-1' : ''}>
              {line}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}; 